package LinkedLlist;

public class TowList {
    static class ListNode{
        public int vale;//节点的值
        public ListNode next;//下一个结点的地址
        public ListNode prev;//上一个节点的地址

    public ListNode(int vale) {
            this.vale = vale;
        }
    }
    public ListNode head;
    public ListNode last;
    //遍历链表打印
    public void display(){
        ListNode cur = head;
        while (cur!=null){
            System.out.println(cur.vale+" ");
            cur=cur.next;
        }
    }
    //求链表的长度
    public int size(){
        int count =0;
        ListNode cur = head;
        while (cur!=null){
            cur=cur.next;
            count++;
        }
        return count;
    }
    //查找是否包含关键字key是否在单链表当中
   public boolean contains(int key){
       ListNode cur = head;
       while (cur!=null){
           if (cur.vale==key){
               return true;
           }
           cur =cur.next;
       }
       return false;
    }
    //头插法
   public void addFirst(int data){
        ListNode node = new ListNode(data);
        if (head==null){
            head = node;
            last = node;
        }else {
            head.prev =node;
            node.next =head;
            head =node;
        }
  }
  //尾插法
         public void addLast(int data){
             ListNode node = new ListNode(data);
             if (head==null){
                 head = node;
                 last = node;
             }else {
                 last.next =node;
                 node.prev =last;
                 last =node;
             }
 }
 //任意位置插入,第一个数据节点为0号下标
  public void addIndex(int index,int data){
        if(index<0||index>size()){
            System.out.println("下标错误");
            return;
        }
      ListNode node = new ListNode(data);
      if (head==null){
          head = node;
          last = node;
      }
      ListNode cur = head;
      while (index!=0){
          cur = cur.next;
          index--;
      }
     node.next=cur.next;
      node.prev=cur;
      cur.next=node;
  }
    public void clear() {
        ListNode cur =head;

        while (cur!=null){
            ListNode curNext =cur.next;
            cur.next =null;
            cur.prev =null;
           cur = curNext;


        }
        head = null;
        last =null;
 }

}
